package com.example.parkdemo.news

import androidx.lifecycle.MutableLiveData
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.base.mvvm.BaseViewModel
import com.example.base.net.ApiService
import com.example.base.net.getService
import com.example.base.user.NewsParamItem
import com.example.base.user.VideoBean
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import okhttp3.RequestBody

import javax.inject.Inject

@HiltViewModel
class NewsViewModel @Inject constructor(
    val apiService: ApiService
) : BaseViewModel() {
    val NewsSuccess by lazy { MutableLiveData<String>() }
    fun News(body: RequestBody) {
        executeNetWork(
            { apiService.news(body) }, NewsSuccess::postValue
        )
    }

    val AddNewsSuccess by lazy { MutableLiveData<String>() }
    fun addNews(body: RequestBody) {
        executeNetWork(
            { apiService.addNews(body) }, AddNewsSuccess::postValue
        )
    }

    fun getNewsPagingData(): Flow<PagingData<NewsParamItem>> {
        return Repo.getNewsPagingData()
    }
}

object Repo {
    private const val PAGE_SIZE = 5
    private val apiService = getService<ApiService>()

    fun getNewsPagingData(): Flow<PagingData<NewsParamItem>> {
        return Pager(config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = { NewsPagingSource(apiService) }).flow
    }
}